package cn.itsource.basic.service.impl;

import cn.itsource.basic.domain.VerificationConstant;
import cn.itsource.basic.service.IVerificationCodeService;
import cn.itsource.basic.util.SendMsgUtils;
import cn.itsource.basic.util.StrUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class VerificationCodeServiceImpl implements IVerificationCodeService {
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 发送注册验证码
     * 验证码需求：
     *      1.后台随机产生4个字符
     *      2.1分钟以内只能发送1次验证码
     *      3.超过1分钟，但在5分钟以内，发送的验证码依然是第一次产生的验证码字符
     *      4.超过了5分钟以后，产生全新的验证码
     * @return
     */
    @Override
    public void sendVerificationCode(String phone) throws Exception {
        sndCode(phone,phone+":"+VerificationConstant.USER_REG);


    }

    @Override
    public void sendbandVerificationCode(String phone) throws Exception {
        sndCode(phone,phone+":"+VerificationConstant.USER_LOGIN);
    }

    public void sndCode(String phone,String key) throws Exception {
        String randStr = StrUtils.getRandomString(4);//创建内容为空字符串对象randStr

        String valuecode =(String) redisTemplate.opsForValue().get(key);
        if(!StringUtils.isEmpty(valuecode)){
            String begintime = valuecode.split(":")[1];
            if((System.currentTimeMillis() - Long.valueOf(begintime)) <= (60 * 1000)){
                throw  new Exception("一分钟只能发送一次验证码");
            }
            randStr = valuecode.split(":")[0];
        }
        redisTemplate.opsForValue().set( key, randStr+":"+System.currentTimeMillis(),5, TimeUnit.MINUTES);
        //randStr = "我是陈冠希呀，我现在 LA，我遇到一班很h很h的人呀，The gangster， 我现在需要你的帮助，" +
        //"wxzzsbk！，我向你敬礼 ，Salute，懂我意思吗？"+randStr;
        randStr = "你的验证码是："+randStr;
        System.out.println(randStr);
        SendMsgUtils.send(phone, randStr);

    }
}
